'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';


interface LoginProps {
  setLoginError?: (error: string) => void;  // 使setLoginError成为可选属性
}

const Login: React.FC<LoginProps> = ({ setLoginError }) => {
  const router = useRouter();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError('');

    try {
      const response = await fetch(`${process.env.NEXT_PUBLIC_API_ENDPOINT}/api/collections/users/auth-with-password`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          identity: email,
          password: password,
        }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.message || '登录失败');
      }

      // 保存 token 到 localStorage
      localStorage.setItem('token', data.token);
      localStorage.setItem('user_id',data.record.id);
      console.log('登录成功:', data.record);
      
      // 登录成功后跳转到主页
      router.push('/');
      alert('登录成功！');
    } catch (err) {
      setError((err as Error).message);
      if (setLoginError) {
        setLoginError((err as Error).message);
      } else {
        // 处理 setLoginError 未定义的情况
      }
      
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="flex flex-col items-center justify-center h-screen">
      <h2 className="text-2xl font-bold mb-4">登录</h2>
      <form onSubmit={handleLogin} className="flex flex-col space-y-4">
        <input
          type="email"
          placeholder="邮箱"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          required
          className="border p-2 rounded"
        />
        <input
          type="password"
          placeholder="密码"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          required
          className="border p-2 rounded"
        />
        {error && <p className="text-red-500">{error}</p>}
        <button
          type="submit"
          disabled={loading}
          className={`bg-blue-500 text-white p-2 rounded ${loading ? 'opacity-50' : ''}`}
        >
          {loading ? '登录中...' : '登录'}
        </button>
        <button
        onClick={() => router.push('/register')}
        className={`mt-4 bg-gray-500 text-white p-2 rounded ${loading ? 'opacity-50' : ''}`}
      >
        注册
      </button>
      </form>
    
    </div>
  );
};

export default Login; 